﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Interface.Utility.Helper
{

    public static class ConvertHelper
    {
        public static string ToStr(this object value, string defaultV = "")
        {
            try
            {
                return Convert.ToString(value);
            }
            catch { return defaultV; }
        }

        public static double ToDouble(this object value, double defaultV = 0)
        {
            try
            {
                return Convert.ToDouble(value);
            }
            catch { return defaultV; }
        }

        public static float ToFloat(this object value, float defaultV = 0)
        {
            try
            {
                return Convert.ToSingle(value);
            }
            catch { return defaultV; }
        }

        public static int ToInt(this object value, int defaultV = 0)
        {
            try
            {
                return Convert.ToInt32(value);
            }
            catch { return defaultV; }
        }

        public static byte ToByte(this object value, byte defaultV = 0)
        {
            try
            {
                return Convert.ToByte(value);
            }
            catch { return defaultV; }
        }

        public static bool ToBool(this object value, bool defaultV = false)
        {
            if (value == null) { return false; }

            string bitStr = value.ToString().ToLower();

            if (bitStr == "true" || bitStr == "yes")
            {
                return true;
            }

            if (bitStr.ToInt() == 1) { return true; }

            return false;
        }

        public static DateTime ToDate(this object value)
        {
            try
            {
                return DateTime.Parse(value.ToString());
            }
            catch { return new DateTime(1970, 1, 1); }
        }

        public static string ToDateLongStr(this object value, string defaultV = "")
        {
            try
            {
                return DateTime.Parse(value.ToString()).ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo);
            }
            catch { return defaultV; }

        }

        public static string ToDateShortStr(this object value, string defaultV = "")
        {
            try
            {
                return DateTime.Parse(value.ToString()).ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
            }
            catch { return defaultV; }
        }

        public static string ToDateStr(this object value, string format)
        {
            try
            {
                return DateTime.Parse(value.ToString()).ToString(format, DateTimeFormatInfo.InvariantInfo);
            }
            catch { return string.Empty; }
        }
    }
}